import db from '../utils/dbconf'
import { SQL_ERROR } from '../server.config.js'
const TABLE_NAME = 'course'

export default{
  sync: async ({body:{courses}},res) => {
    try {
      let data = {}
      for(let name of courses){
        const id = await db.table(TABLE_NAME).thenAdd({name},{name},false)
        data[name] = id
      }
      return res.send({
        code:200,
        data
      })
    } catch (error) {
      return res.send(SQL_ERROR)
    }
  },
  get:async ({query}, res) => {
    try{
      const { key,size,page } = query
      const wherefilter = {name:['LIKE',`%${key||''}%`]}
    	const course = await db.table(TABLE_NAME)
        .where(wherefilter)
        .page(page,size)
        .select()
      const total = await db.table(TABLE_NAME)
        .where(wherefilter)
        .count('id')
      return res.send({
        code:200,
        data:{ course,total }
      })
    }catch(error){
    	return res.send(SQL_ERROR)
    }
  },
  add:async ({body}, res) => {
    return res.send(SQL_ERROR)
  },
  delete:async ({params:{id}}, res) => {
    const ok = await db.table(TABLE_NAME)
      .where({id})  
      .delete()
    return res.send({ code:ok?200:500 })
  },
  update:async ({body}, res) => {
    return res.send(SQL_ERROR)
  }
}